<template>
  <div class="my-card">
    <div class="toolbar">
      <DatePicker
        :options="options"
        :getData="getData"
      >
      </DatePicker>
      <el-button class="my-btn" type="primary" @click="openStatus">状态配置</el-button>
    </div>
    <v-chart class="chartBox" :options="lineOption"/>
    <el-container style="display:flex;flex-direction:column;">
      <el-table
        :data="tapData"
        style="width: 100%"
        :default-sort = "{prop: 'date', order: 'descending'}"
        >
        <el-table-column
          prop="time"
          label="时间"
          sortable
          width="180">
        </el-table-column>
        <el-table-column
          prop="data"
          label="开启度（%）">
        </el-table-column>
      </el-table>
    </el-container>
    <el-dialog :visible.sync="dialogVisible" :append-to-body="true" :title="`XX阀门当前状态 ${tapData[0]?tapData[0].time:'暂无'}`">
      <v-chart style="width: 300px;height: 300px;display: inline-block;" :options="gaugeOption"/>
      <el-form class="form" :inline="true">
        <el-form-item>
          <el-input v-model="tapOpenDegree" placeholder="修改阀门开启度(%)"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveTapOpenDegree">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import ECharts from 'vue-echarts/components/ECharts'
import 'echarts/lib/chart/gauge'
import echartsCommonOptions from '../../../config/echartsCommonOptions'
import { defaultsDeep } from 'lodash'
import moment from 'moment'
import axios from 'axios'
import DatePicker from '../../../components/DatePicker.vue'
import { getTapOpenData, setTapOpenStatus } from '../../model'

export default {
  data () {
    return {
      valveId: 'SP-PMP-002',
      defaultDate: [moment().subtract(1, 'M').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')],
      tapData: [],
      options: [{
        text: '最近一月',
        range: [moment().subtract(1, 'M').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
      }, {
        text: '最近一年',
        range: [moment().subtract(1, 'y').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
      }],
      valueId: '',
      dialogVisible: false,
      lineOption: {},
      gaugeOption: {},
      tapOpenDegree: ''
    }
  },
  components: {
    'v-chart': ECharts,
    DatePicker
  },
  mounted () {
    this.getData(this.defaultDate)
  },
  methods: {
    openStatus () {
      this.dialogVisible = true
      if(this.tapData[0]) {
        this.initGauge(this.tapData[0].value)
      }
    },
    initGauge (data) {
      let highlight = '#03b7c9'
      let item = {
        name: '阀门开启度(%)',
        value: (data * 100),
        unit: '%',
        pos: ['50%', '50%'],
        range: [10, 100],
        splitNum: 9
      }
      this.gaugeOption = {
        series: [
          // 外围刻度
          {
            type: 'gauge',
            center: item.pos,
            radius: '80%', // 1行3个
            splitNumber: item.splitNum || 10,
            min: item.range[0],
            max: item.range[1],
            startAngle: 225,
            endAngle: -45,
            axisLine: {
              show: true,
              lineStyle: {
                width: 2,
                shadowBlur: 0,
                color: [
                  [1, highlight]
                ]
              }
            },
            axisTick: {
              show: true,
              lineStyle: {
                color: highlight,
                width: 1
              },
              length: -5,
              splitNumber: 10
            },
            splitLine: {
              show: true,
              length: -14,
              lineStyle: {
                color: highlight
              }
            },
            axisLabel: {
              distance: -20,
              textStyle: {
                color: this.highlight,
                fontSize: '14',
                fontWeight: 'bold'
              }
            },
            pointer: {
              show: 0
            },
            detail: {
              show: 0
            }
          },
          // 内侧指针、数值显示
          {
            name: item.name,
            type: 'gauge',
            center: item.pos,
            radius: '80%',
            startAngle: 225,
            endAngle: -45,
            min: item.range[0],
            max: item.range[1],
            axisLine: {
              show: true,
              lineStyle: {
                width: 16,
                color: [
                  [1, 'rgba(255,255,255,.1)']
                ]
              }
            },
            axisTick: {
              show: 0
            },
            splitLine: {
              show: 0
            },
            axisLabel: {
              show: 0
            },
            pointer: {
              show: true,
              length: '105%'
            },
            detail: {
              show: true,
              offsetCenter: [0, '100%'],
              textStyle: {
                fontSize: 16,
                color: '#000'
              },
              formatter: [
                '{value} ' + (item.unit || ''),
                '{name|' + item.name + '}'
              ].join('\n'),
              rich: {
                name: {
                  fontSize: 12,
                  lineHeight: 30,
                  color: '#000'
                }
              }
            },
            itemStyle: {
              normal: {
                color: highlight
              }
            },
            data: [{
              value: item.value
            }]
          }
        ]
      }
    },
    initEchart () {
      this.lineOption = defaultsDeep({
        dataset: [{
          source: this.tapData,
          dimensions: ['time', 'data']
        }],
        xAxis: {type: 'category'},
        yAxis: {
          name: '开启度（%）',
          type: 'value',
          axisTick: {
            alignWithLabel: true
          }
        },
        series: [
          {
            name: '阀门状态',
            type: 'line',
            markPoint: {
              symbolSize: 40,
              data: [
                {type: 'max', name: '最大值'},
                {type: 'min', name: '最小值'}
              ]
            }
          }
        ]
      }, echartsCommonOptions.lineOptions)
    },
    getData (date) {
      let params = {
        valveId: this.valveId,
        startTime: moment(date[0]).format('x'),
        endTime: moment(date[1]).format('x')
      }
      getTapOpenData(params).then(res => {
        this.tapData = res.data.data.historyData
        this.initEchart()
      })
    },
    saveTapOpenDegree () {
      this.dialogVisible = false
      setTapOpenStatus({
        valveId: this.valveId,
        curDegree: (this.tapOpenDegree % 10)
      }).then((res) => {
        if (res.data.code === 0) {
          this.$message({
            message: '设置成功',
            type: 'success'
          })
        } else {
          this.$message({
            message: '设置失败，请重试',
            type: 'warning'
          })
        }
      })
    }
  }
}
</script>

<style lang="sass" scoped>
/deep/ .el-dialog__body
  text-align: center;
.my-card
  width: 100%;
  background-color: #fff;
  padding: 15px;
  margin: 10px;
  .gauge-chart
    width: 300px;
    height: 200px;
  .toolbar
    position: relative;
    .my-btn
      position: absolute;
      top: 0;
      right: 0;
      margin: 0 10px;
  .dialogform
    padding: 16px
  .chartBox
    height: 350px;
    width: 100%;
  /deep/ .el-date-editor
    width: 350px;
    justify-content: space-between;
</style>
